package com.ctrl.riveradministrator.http.download;

import android.content.Context;
import android.os.Environment;
import android.util.Log;

import com.ctrl.riveradministrator.common.Constants;
import com.ctrl.riveradministrator.http.APIService;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;

import io.reactivex.Observer;
import io.reactivex.Scheduler;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okio.BufferedSink;
import okio.Okio;
import okio.Sink;

public class DownloadUtil {

    public void downloadFile(Context context, APIService apiService, final long range, final String url,
                             final String fileName, final DownloadListener downloadListener) {
        Log.d("DOWNLOAD", "DOWNLOAD");
        File file = new File(Constants.APP_ROOT_PATH + Constants.DOWNLOAD_DIR, fileName);
        String totalLength = "-";
        if (file.exists()) {
            totalLength += file.length();
        }
        Log.d("DOWNLOAD", "bytes=" + range + "," + totalLength + "," + url);
        apiService.download(url)
                .subscribe(new Observer<ResponseBody>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        Log.d("DOWNLOAD", "onSubscribe");
                    }

                    @Override
                    public void onNext(ResponseBody responseBody) {
                        Log.d("DOWNLOAD", "onNext");
                        FileOutputStream fos = null;
                        InputStream inputStream = null;
                        long total = 0;
                        long responseLength = 0;
                        try {
                            byte[] buf = new byte[2048];
                            int len = 0;
                            responseLength = responseBody.contentLength();
                            inputStream = responseBody.byteStream();
                            Log.d("DOWNLOAD", "responseLength" + responseLength);
                            String filePath = Constants.APP_ROOT_PATH + Constants.DOWNLOAD_DIR;
                            File file = new File(filePath, fileName);
                            File dir = new File(filePath);
                            if (!dir.exists()) {
                                dir.mkdirs();
                            }
                            fos = new FileOutputStream(file);

                            int progress = 0;
                            int lastProgress = 0;
                            while ((len = inputStream.read(buf)) != -1) {
                                fos.write(buf, 0, len);
                                total += len;
                                lastProgress = progress;
                                progress = (int) (total * 100 / responseLength);
                                if (progress > 0 && progress != lastProgress) {
                                    downloadListener.onProgress(progress);
                                }
                            }
                            downloadListener.onCompleted(file);
                            SPDownloadUtil.getInstance(context).clear();
                        } catch (Exception e) {
                            downloadListener.onError(e.getMessage());
                            e.printStackTrace();
                        } finally {
                            try {
                                if (fos != null) {
                                    fos.close();
                                }

                                if (inputStream != null) {
                                    inputStream.close();
                                }

                            } catch (Exception e) {
                                e.printStackTrace();
                            }

                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        downloadListener.onError(e.toString());
                    }

                    @Override
                    public void onComplete() {

                    }
                });
        /*apiService.download("bytes=" + range + totalLength, url)
                .subscribe(new Observer<ResponseBody>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        Log.d("DOWNLOAD","onSubscribe");
                    }

                    @Override
                    public void onNext(ResponseBody body) {
                        Log.d("DOWNLOAD","onNext");
                        RandomAccessFile randomAccessFile = null;
                        InputStream inputStream = null;
                        long total = range;
                        long responseLength = 0;
                        try {
                            byte[] buf = new byte[2048];
                            int len = 0;
                            responseLength = body.contentLength();
                            inputStream = body.byteStream();
                            Log.d("DOWNLOAD","responseLength"+responseLength);
                            String filePath = Constants.APP_ROOT_PATH + Constants.DOWNLOAD_DIR;
                            File file = new File(filePath, fileName);
                            File dir = new File(filePath);
                            if (!dir.exists()) {
                                dir.mkdirs();
                            }
                            randomAccessFile = new RandomAccessFile(file, "rwd");
                            if (range == 0) {
                                randomAccessFile.setLength(responseLength);
                            }
                            randomAccessFile.seek(range);

                            int progress = 0;
                            int lastProgress = 0;
                            while ((len = inputStream.read(buf)) != -1) {
                                randomAccessFile.write(buf, 0, len);
                                total += len;
                                SPDownloadUtil.getInstance(context).save(url, total);
                                lastProgress = progress;
                                progress = (int) (total * 100 / randomAccessFile.length());
                                if (progress > 0 && progress != lastProgress) {
                                    downloadListener.onProgress(progress);
                                }
                            }
                            downloadListener.onCompleted(file);
                            SPDownloadUtil.getInstance(context).clear();
                        } catch (Exception e) {
                            downloadListener.onError(e.getMessage());
                            e.printStackTrace();
                        } finally {
                            try {
                                if (randomAccessFile != null) {
                                    randomAccessFile.close();
                                }

                                if (inputStream != null) {
                                    inputStream.close();
                                }

                            } catch (Exception e) {
                                e.printStackTrace();
                            }

                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        downloadListener.onError(e.toString());
                    }

                    @Override
                    public void onComplete() {

                    }
                });*/
    }

    public void downloadFile(String u, DownloadListener downloadListener) {
        //下载路径，如果路径无效了，可换成你的下载路径
        final String url = Constants.BASE_URL_ + u;
        final long startTime = System.currentTimeMillis();
        Log.i("DOWNLOAD", "startTime=" + startTime);

        Request request = new Request.Builder().url(url).build();
        new OkHttpClient().newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                // 下载失败
                e.printStackTrace();
                Log.i("DOWNLOAD", "download failed");
                downloadListener.onError("下载错误");
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
               /* downloadListener.onProgress(1);
                Sink sink = null;
                BufferedSink bufferedSink = null;
                try {
                    File dest = new File(Constants.APP_ROOT_PATH + Constants.DOWNLOAD_DIR,
                            url.substring(url.lastIndexOf("/") + 1));
                    sink = Okio.sink(dest);
                    bufferedSink = Okio.buffer(sink);

                    bufferedSink.writeAll(response.body().source());
                    bufferedSink.close();
                    Log.i("DOWNLOAD", "download success");
                    Log.i("DOWNLOAD", "totalTime=" + (System.currentTimeMillis() - startTime));
                    downloadListener.onCompleted(dest);
                } catch (Exception e) {
                    e.printStackTrace();
                    Log.i("DOWNLOAD", "download failed");
                    downloadListener.onError("下载错误");
                } finally {
                    if (bufferedSink != null) {
                        bufferedSink.close();
                    }

                }*/
                InputStream is = null;
                byte[] buf = new byte[2048];
                int len = 0;
                FileOutputStream fos = null;

                //储存下载文件的目录
               File dir = new File(Constants.APP_ROOT_PATH + Constants.DOWNLOAD_DIR,
                        url.substring(url.lastIndexOf("/") + 1));
                File file = new File(dir,url.substring(url.lastIndexOf("/") + 1));
                if (!dir.exists()) {
                    dir.mkdirs();
                }
                try {

                    is = response.body().byteStream();
                    long total = response.body().contentLength();
                    fos = new FileOutputStream(file);
                    long sum = 0;
                    while ((len = is.read(buf)) != -1) {
                        fos.write(buf, 0, len);
                        sum += len;
                        int progress = (int) (sum * 1.0f / total * 100);
                        //下载中更新进度条
                        downloadListener.onProgress(progress);
                    }
                    fos.flush();
                    //下载完成
                    downloadListener.onCompleted(file);
                } catch (Exception e) {
                    e.printStackTrace();
                    downloadListener.onError(e.getMessage());
                } finally {
                    try {
                        if (is != null) {
                            is.close();
                        }
                        if (fos != null) {
                            fos.close();
                        }
                    } catch (IOException e) {

                    }

                }
            }
        });
    }
}
